// 创建一个闭包 
(function($) {
	function CronExp($this){
		// 配置
		this.configs = [{"title": "分钟", "id": "Min", "size": 59, "begin": 0}, 
					{"title": "小时", "id": "Hour", "size": 24, "begin": 1}, 
					{"title": "日", "id": "Day", "size": 31, "begin": 1}, 
					{"title": "月", "id": "Mon", "size": 12, "begin": 1}, 
					{"title": "星期", "id": "Week", "size": 7, "begin": 1}];
		
		// 秒，分，时，日，月，星期
		this.exSec, this.exMin, this.exHour, this.exDay, this.exMon, this.exWeek;
		// 各切换按钮
		this.minStart, this.minEnd;
		// 0分，1时，2日，3月，4星期
		this.radios = [];
	
		this.target = $this;
		// GUID
		this.guid = CronExp.guid();
		// 生成表达式文本框
		this.expInput;
		
		// 选择卡
		this.tabs = [];
		
		// 按钮
		this.uiButton;
		
		// 窗口
		this.uiWindow;
	}
	
	// GUID
	CronExp.guid = function () {
		function S4() {
		   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
		}
		return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
	}
	
	// UI添加按钮
	CronExp.prototype.createUIButton = function() {
		var $this = this;
		var height = this.target.height();
		if(height == 0){
			height = 16;
		}
		var height = height 
					+ parseInt(this.target.css("padding-bottom"))
					+ parseInt(this.target.css("padding-top"))
					+ parseInt(this.target.css("border-bottom-width"))
					+ parseInt(this.target.css("border-top-width"));
					
		this.target.addClass("cron-input");
		var $btn = $("<input>").attr("type", "button")
					.height(height)
					.addClass("cron-button")
					.val("...")
					.insertAfter(this.target)
					.toggler(function(event) {
						$this.show();
					}, function(event) {
						$this.hide();
					});
		this.uiButton = $btn;
	};
	
	// 显示
	CronExp.prototype.show = function(){
		this.center(this.uiWindow);
		this.uiWindow.show();
	};
	
	// 隐藏
	CronExp.prototype.hide = function(){
		this.uiWindow.hide();
	};
	
	// 添加window的UI
	CronExp.prototype.createUIWindow= function(){
		var $this = this;
		
		var $panel = $( "<div>" )
					.addClass("mini-panel")
					.addClass("mini-window-drag")
					.css("display", "none")
					.css("z-index", 99999)
					.appendTo($("body"));
		var $panelBorder =  $( "<div>" )
					.addClass("mini-panel-border")
					.appendTo($panel);
		var $panelHeader =  ( this.uiDialog = $( "<div>" ) )
					.addClass("mini-panel-header")
					.appendTo($panelBorder);
		var $panelBody =  $( "<div>" )
					.addClass("mini-panel-body")
					.css("padding", "0px")
					.css("overflow", "hidden")
					.css("height", "auto")
					.appendTo($panelBorder);
		var $panelToolbar =  $( "<div>" )
					.addClass("mini-toolbar")
					.appendTo($panelBorder);
		var $panelHeaderInner =  $( "<div>" )
					.addClass("mini-panel-header-inner")
					.appendTo($panelHeader);
		var $panelHeaderTitle =  $( "<div>" )
					.addClass("mini-panel-title")
					.text("定时表达式生成器")
					.appendTo($panelHeaderInner);
		var $panelTools =  $( "<div>" )
					.addClass("mini-tools")
					.appendTo($panelHeaderTitle);
		var $panelToolsClose=  $( "<span>" )
					.addClass("mini-tools-close")
					.appendTo($panelTools)
					.click(function(){
						$panel.css("display", "none");
					});

		var $panelBodyContext=  $("<div>")
					.css("width", "500px")
					.css("height", "410px")
					.appendTo($panelBody);
		
	
		$tabHeader = $("<div>").addClass("tabs-header").appendTo($panelBodyContext);
		var $tabs = $("<ul>").addClass("tabs").appendTo($tabHeader);
		var $tabPanels = $("<div>").addClass("tabs-panels").appendTo($panelBodyContext);
		
		
		for(var i in this.configs){
			var title = this.configs[i].title;
			// 添加选项卡
			var $tab = $("<li>");
			if(i == 0){
				$tab.addClass("tabs-selected");
			}
			$tab.appendTo($tabs);
			var $a = $("<a>")
					.addClass("tabs-inner")
					.attr("index", i)
					.attr("id", "tabs-a" + (this.guid + i ))
					.appendTo($tab);
			var $span = $("<span>").addClass("tabs-title").text(title).appendTo($a);
			
			// 添加选项卡内容
			var $tabPanel = $("<div>")
							.addClass("panel")
							.attr("id", "tabs-panel" + (this.guid + i ))
							.appendTo($tabPanels);
			if(i == 0){
				$tabPanel.css("display", "block");
			}else{
				$tabPanel.css("display", "none");
			}
			
			var $minul = $("<ul>").css("height", "180px").appendTo($tabPanel);
			var $minli1;
			if(this.configs[i].title == '分钟'){
				$minli1 = $("<li>").appendTo($minul);
						$("<input type=\"radio\" name=\"r" + (this.guid + this.configs[i].id) + "\" id=\""+(this.guid + i )+"Id\" checked=\"checked\" value=\"*\" />").appendTo($minli1)
						$("<label for=\""+(this.guid + i )+"Id\">周期 从</label>").appendTo($minli1);			
				this.minStart = $("<input class=\"easyui-numberspinner\" data-options=\"min:0,max:60\" style=\"width:80px;\" value=\"0\">").appendTo($minli1);
						$("<label>分钟开始,每</label> ").appendTo($minli1);
				this.minEnd = $("<input class=\"easyui-numberspinner\" data-options=\"min:1,max:60\" style=\"width:80px;\" value=\"0\"/>").appendTo($minli1);
						$("<label>分钟执行一次</label>").appendTo($minli1);
			} else {
				$minli1 = $("<li>").appendTo($minul);
						$("<input type=\"radio\" name=\"r" + (this.guid + this.configs[i].id) + "\" id=\""+(this.guid + i ) +"Id\" checked=\"checked\" value=\"*\" />").appendTo($minli1);
						$("<label for=\""+(this.guid + i )+"Id\">每" + this.configs[i].title + "</label>").appendTo($minli1);
			}
			var $minli2 = $("<li>").appendTo($minul);
			var $radio = $("<input type=\"radio\" name=\"r" + (this.guid + this.configs[i].id) + "\" id=\""+(this.guid + i )+"Id2\" value=\"c\">").appendTo($minli2);
						$("<label for=\""+(this.guid + i )+"Id2\">指定</label>").appendTo($minli2);
						
			this.radios.push($radio);
			
			var $tpanel = $("<div class=\"panelMain\"></div>").appendTo($minul);
						
			var j = this.configs[i].begin;
			while(j <= this.configs[i].size){
				$("<input>")
				.attr("type", "checkbox")
				.attr("value", j)
				.attr("name", this.configs[i].id+"chk")
				.attr("disabled", "disabled")
				.attr("id", (this.guid + i )+j)
				.css("margin", "3px 3px 3px 4px")
				.appendTo($tpanel);
				$("<label>")
				.attr("for", (this.guid + i )+j)
				.css("width", "20px")
				.text(j)
				.appendTo($tpanel);
				j++;
			}
			this.tabs.push({tab: $a, context: $tabPanel});
			
			$a.click(function(){// 切换选项卡
				for(var i in $this.tabs){
					if($this.tabs[i].tab.attr("id") == $(this).attr("id")){
						$this.tabs[i].tab.parent().addClass("tabs-selected");
						$this.tabs[i].context.css("display", "block");
					}else{
						$this.tabs[i].tab.parent().removeClass("tabs-selected");
						$this.tabs[i].context.css("display", "none");
					}
				}
			});
			
			$minli2.click(function(){
				$(this).parent().parent().find(".panelMain input:checkbox").attr("disabled", false);
			});
			$minli1.click(function(){
				$(this).parent().parent().find(".panelMain input:checkbox").attr("disabled", true);
			});
		}
		
		var $genDiv = $("<div>")
					.css("margin", "10px 0")
					.css("text-align", "center")
					.appendTo($panelBodyContext);
		var $genA = $("<a>")
					.addClass("mini-button")
					.attr("href", "javascript:void(0)")
					.appendTo($genDiv)
					.click(function(){
						$this.build();
					});
					
		var $genBtn = $("<span>")
					.addClass("mini-button-text")
					.text("生成表达式")
					.attr("id", "btnGen")
					.appendTo($genA);
						
		var $cres = $("<div>").addClass("Cres").appendTo($panelBodyContext);
		var $cresfieldset = $("<fieldset>").appendTo($cres);
		var $cresfieldsetlegend = $("<legend>").text("表达式").appendTo($cresfieldset);
		var $cresdiv = $("<div>").appendTo($cresfieldset);
		var $crestable = $("<table>").appendTo($cresdiv);
		$("<tr>").append($("<td>"))
				.append($("<td>").text("秒"))
				.append($("<td>").text("分钟"))
				.append($("<td>").text("小时"))
				.append($("<td>").text("日"))
				.append($("<td>").text("月"))
				.append($("<td>").text("星期"))
				.appendTo($crestable);
		
		this.exSec = $("<input>").addClass("exSec");
		this.exMin = $("<input>").addClass("exMin");
		this.exHour = $("<input>").addClass("exHour");
		this.exDay = $("<input>").addClass("exDay");
		this.exMon = $("<input>").addClass("exMon");
		this.exWeek = $("<input>").addClass("exWeek");
		
		$("<tr>").append($("<td>").text("表达式字段:"))
				.append($("<td>").append(this.exSec))
				.append($("<td>").append(this.exMin))
				.append($("<td>").append(this.exHour))
				.append($("<td>").append(this.exDay))
				.append($("<td>").append(this.exMon))
				.append($("<td>").append(this.exWeek))
				.appendTo($crestable);
				
		var $expInput = $("<input>").addClass("expInput").css("width", "370px");
		$("<tr>").append($("<td>").text("定时表达式:"))
				.append($("<td>").attr("colspan", 6).append($expInput))
				.appendTo($crestable);
				
		this.expInput = $expInput;
		
		var $buttonDone = $("<a class=\"mini-button\" href=\"javascript:void(0)\"><span class=\"mini-button-text\">确定</span></a>")
					.appendTo($panelToolbar)
					.click(function(){
						$this.done();
					});
					
		$("<span style=\"display:inline-block;width:25px;\"></span>")
					.appendTo($panelToolbar);
		var $buttonClose = $("<a class=\"mini-button\" href=\"javascript:void(0)\"><span class=\"mini-button-text\">取消</span></a>")
					.appendTo($panelToolbar)
					.click(function(){
						$this.uiButton.trigger("click");
					});
					
		this.uiWindow = $panel;	
	};
	
	// 居中
	CronExp.prototype.center = function(obj) {
		 var screenWidth = $(window).width(), screenHeight = $(window).height();  	//当前浏览器窗口的 宽高
		 var scrolltop = $(document).scrollTop();									//获取当前窗口距离页面顶部高度
	
		 var objLeft = (screenWidth - obj.width())/2 ;
		 var objTop = (screenHeight - obj.height())/2 + scrolltop;
 
		 obj.css({left: objLeft + 'px', top: objTop + 'px','display': 'block'});
		 //浏览器窗口大小改变时
		 $(window).resize(function() {
			 screenWidth = $(window).width();
			 screenHeight = $(window).height();
			 scrolltop = $(document).scrollTop();
			
			 objLeft = (screenWidth - obj.width())/2 ;
			 objTop = (screenHeight - obj.height())/2 + scrolltop;
			
			 obj.css({left: objLeft + 'px', top: objTop + 'px','display': 'block'});
			
		 });
		 //浏览器有滚动条时的操作、
		 $(window).scroll(function() {
			 screenWidth = $(window).width();
			 screenHeight = $(widow).height();
			 scrolltop = $(document).scrollTop();
			
			 objLeft = (screenWidth - obj.width())/2 ;
			 objTop = (screenHeight - obj.height())/2 + scrolltop;

			 obj.css({left: objLeft + 'px', top: objTop + 'px','display': 'block'});
		 });
	}
	
	// 完成
	CronExp.prototype.done= function(){
		var txtCron = this.expInput.val();
		this.target.val(txtCron);
		this.uiButton.trigger("click");
	};
	

	// 生成表达式
	CronExp.prototype.build = function(){
		this.exSec.val(0);
		var mini = this.getMin();
		this.exMin.val(mini);
		var hour = this.getHour();
		this.exHour.val(hour);
		var day = this.getDay();
		this.exDay.val(day);
		var mon = this.getMon();
		this.exMon.val(mon);
		var week = this.getWeek();
		this.exWeek.val(week);
		var str = "0 "+mini+" "+hour+" "+day+" "+mon+" "+week;
		if(day != '*' && week != '*' && week != '?'){
			alert("日和星期冲突，不能同时指定日和星期");
			return false;
		}
		if(day != '*' && mon != '*'){
			alert("日和月冲突，不能同时指定日和月");
			return false;
		}
		
		this.expInput.val(str);
	}
	
	// 得到分钟
	CronExp.prototype.getMin = function(){
		if(this.radios[0].prop("checked")==true){
			var cks = this.uiWindow.find("input[name='Minchk']:checked");
			if(cks.length==1){
				var v = cks[0].value;
				if(v && v != null && v != '') return v;
			}else{
				var vs = "";
				for(var i=0;i<cks.length;i++){
					vs+=cks[i].value;
					if(i<cks.length-1){
						vs+=",";
					}
				}
				if(vs != "") return vs;
			}
		}
		
		if(this.minEnd.val() != '0'){
			return this.minStart.val()+"/"+this.minEnd.val();
		}
		return this.minStart.val();
	}
	
	// 得到小时
	CronExp.prototype.getHour = function(){
		if(this.radios[1].prop("checked")==true){
			var cks = this.uiWindow.find("input[name='Hourchk']:checked");
			if(cks.length==1){
				var v = cks[0].value;
				if(v && v != null && v != '') return v;
			}else{
				var vs = "";
				for(var i=0;i<cks.length;i++){
					vs+=cks[i].value;
					if(i<cks.length-1){
						vs+=",";
					}
				}
				if(vs != '') return vs;
			}
		}
		return "*";
	}
	
	// 得到日
	CronExp.prototype.getDay = function(){
		if(this.radios[2].prop("checked")==true){
			var v = this.uiWindow.find("input[name='Daychk']:checked").val();
			if(v) return v;
		}
		return "*";
	}

	// 得到月
	CronExp.prototype.getMon = function(){
		if(this.radios[3].prop("checked")==true){
			var v = this.uiWindow.find("input[name='Monchk']:checked").val();
			if(v) return v;
		}
		return "*";
	}
	
	// 得到星期
	CronExp.prototype.getWeek = function(){
		if(this.radios[4].prop("checked")==true){
			var v = this.uiWindow.find("input[name='Weekchk']:checked").val();
			if(v) return v;
		}
		return "?";
	}

	 // 插件的定义 
	 $.fn.cronExp = function(options) {
		debug(this);
		// build main options before element iteration
		var opts = $.extend({}, $.fn.cronExp.defaults, options);
		// iterate and reformat each matched element
		return this.each(function() {
			$this = $(this);
			// build element specific options 
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			
			var exp = new CronExp($this);
			// 按钮
			exp.createUIButton();
			// 窗口
			exp.createUIWindow();		
		});
	};
	 // 私有函数：debugging
	function debug($obj) {
	};
	

	// 插件的defaults
	$.fn.cronExp.defaults = {
		foreground: 'red',
		background: 'yellow'
	};
	// 闭包结束
})(jQuery);

//toggle plugin from caibaojian.com
$.fn.toggler = function( fn, fn2 ) {
	var args = arguments,guid = fn.guid || $.guid++,i=0,
	toggler = function( event ) {
	  var lastToggle = ( $._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
	  $._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
	  event.preventDefault();
	  return args[ lastToggle ].apply( this, arguments ) || false;
	};
	toggler.guid = guid;
	while ( i < args.length ) {
	  args[ i++ ].guid = guid;
	}
	return this.click( toggler );
};